/*
 * main.c
 *
 *  Created on: May 8, 2009
 *      Author: lapoija
 *
 *  Compile using the GCC (GNU Compiler Collection):
 *    gcc -O0 -g3 -pedantic -pedantic-errors -Wall -Werror -c -fmessage-length=0 -std=c99 -D_THREAD_SAFE
 */
#include "thread_extensions.h"
#include <semaphore.h>
#include "producer_test.h"
#include "consumer_test.h"
#include "common.h"
#include "producer_consumer.h"
#include "log.h"

int main(void)
{
   // Thread variables
   pthread_t threadConsume;
   pthread_t threadProduce;
   pthread_attr_t threadAttr; // thread attributes

   // Initialize the thread attributes.
   PTHREAD_ATTR_INIT(&threadAttr);
   pthread_attr_setscope(&threadAttr, PTHREAD_SCOPE_SYSTEM);
   pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);

   // Initialize the shared exit semaphore - used to wait for worker threads to finish
   // before allowing the main thread (and process) to exit.
   SEM_INIT(&exitSem, 0, 0);

   // delete any existing log files
   EraseLog();
   EraseErrorLog();

   // Initialize the shared mutex.
   initMutex();

   // create and start the producer worker thread.
   PTHREAD_CREATE(&threadProduce, &threadAttr, producer_test, NULL);

   // create and start the consumer worker thread.
   PTHREAD_CREATE(&threadConsume, &threadAttr, consumer_test, NULL);

   // wait for all worker threads to exit before allowing the main thread to exit.
   thread_single_barrier(&exitSem, TOTAL_THREAD_COUNT);

   return EXIT_STATUS_SUCCESS;
}
